package cn.ayaka;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

public class DslTest {

    private TransportClient getClient(){
        Settings settings = Settings.builder()
                .put("client.transport.sniff", true).build();
        TransportClient client = null;
        try {
             client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return client;
    }

    @Test
    public void search(){
        //获取连接
        TransportClient client = getClient();
        //指定搜索的索引库
        SearchRequestBuilder searchBuilder = client.prepareSearch("pethome");

        //排序
        searchBuilder.addSort("age", SortOrder.DESC);
        //分页
        searchBuilder.setFrom(0);
        searchBuilder.setSize(10);

        //查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();  // new BoolQueryBuilder();
        //username 为 zs 或者 ww 的(查询)
        boolQueryBuilder.must(QueryBuilders.matchQuery("username", "zs ww"));
        //sex为男，age在10 - 50之间的（过滤）
        boolQueryBuilder
                .filter(QueryBuilders.termQuery("sex", 1))
                .filter(QueryBuilders.rangeQuery("age").gte(10).lte(50));

        //获取结果
        SearchResponse searchResponse = searchBuilder.setQuery(boolQueryBuilder).get();

        //命中,查询到的结果
        SearchHits hits = searchResponse.getHits();

        //获取总的命中数
        long totalHits = hits.getTotalHits();
        System.out.println("查到的总条数："+totalHits);

        //结果列表
        SearchHit[] list = hits.getHits();
        for (SearchHit searchHit : list) {
            //拿到数据
            Map<String, Object> source = searchHit.getSource();
            System.out.println(source);
        }

    }
}
